<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat } from '@/hooks/util'
import * as xyApi from '@/api/xy'
import { message } from 'ant-design-vue'
import AddGroup from './component/addTask.vue'
import TaskList from './component/taskList.vue'
import GoodsList from './component/goodsList.vue'
import TimerList from './component/timerList.vue'
import { Modal } from 'ant-design-vue'
import { EditOutlined, InboxOutlined, AreaChartOutlined } from '@ant-design/icons-vue'
const route = useRoute()

//响应式方面
const containerRef = ref(null) // 用于引用.task-container DOM元素
const ItemRef = ref(null) // 用于引用.task-container DOM元素
const containerStyle = ref({}) // 用于存储.task-container的样式
const updateContainerStyle = () => {
  if (containerRef.value) {
    const ItemRefWidth = 300
    const containerWidth = containerRef.value.offsetWidth
    const num = Math.floor(containerWidth / ItemRefWidth)
    const yushu = (containerWidth - 20 * num) % ItemRefWidth
    const resultWidth = containerWidth - 20 * num - ItemRefWidth * num
    const marginLeft = yushu > 200 ? (resultWidth + yushu) / 2 : resultWidth / 2
    // const marginLeft = resultWidth / 2

    containerStyle.value = {
      marginLeft: `${Math.abs(marginLeft)}px`,
    }
  }
}
const onShowSizeChange = (current: number, pageSize: number) => {
  console.log(current, pageSize)
}

//列表分页操作方面
const pageSize = ref(14)
const currentPage = ref(1)
const total = ref(0)

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  showQuickJumper: boolean
}
let loading = ref<boolean>(false)
const spinning = ref<boolean>(true)
const pagination = ref<Pagination>({ page: 1, pageSize: 10, total: 0, showQuickJumper: true })
//监听
watch(pageSize, newVal => {
  spinning.value = true
  currentPage.value = 1
  pageSize.value = newVal
  getList()
})
watch(currentPage, newVal => {
  spinning.value = true
  currentPage.value = newVal
  getList()
})
const dataSource = ref([])
//获取当前的列表
const getList = async () => {
  try {
    let params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      remark: searchParams.value.remark,
      startState: searchParams.value.startState,
    }
    let { state, data, message: msg } = await xyApi.getTaskListByPolish(params)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })

      dataSource.value = data.list
      total.value = Number(data.totalCount)
      spinning.value = false
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
  spinning.value = false
}
//备注操作
const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}
// 修改备注
const editRemark = async (id: string, remark: string) => {
  let params = { polishId: id, remark: remark }
  try {
    const { state, message: msg } = await xyApi.editAutomatePolishRemark(params)
    if (state === 200) {
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
//开启和关闭任务
const updatedStated = async (item: any, type: any) => {
  try {
    let params = {
      polishId: item.id,
      startState: type,
    }
    let { state, data, message: msg } = await xyApi.editAutomatePolish(params)
    if (state === 200) {
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
//删除任务
const deleteTask = (item: any) => {
  Modal.confirm({
    content: () => '确定删除当前任务?',
    closable: true,
    okText: '确定',
    maskClosable: true,
    async onOk() {
      try {
        let params = {
          polishId: item.id,
        }
        let { state, data, message: msg } = await xyApi.deleteAutomatePolish(params)
        if (state === 200) {
          getList()
        } else {
          message.error(msg)
        }
      } catch (error) {
        message.error('网络请求连接失败~')
      }
    },
    cancelText: () => '取消',
    onCancel() {
      Modal.destroyAll()
    },
  })
}

onMounted(() => {
  getList()
  updateContainerStyle()
  window.addEventListener('resize', updateContainerStyle) //监听当前屏幕 自适应
})

// 列表筛选方面
const formRef = ref()
const searchParams = ref({})
interface FormState {
  remark?: string | undefined
  startState?: string | number
}
const formState = reactive<FormState>({})
import type { SelectProps } from 'ant-design-vue'
const robotStateList = ref<SelectProps['options']>([
  {
    label: '正常',
    value: 1,
  },
  {
    label: '手动关闭',
    value: 0,
  },
])
//检索当前列表
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  spinning.value = true
  formRef.value.validate().then(() => {
    searchParams.value.remark = formState.remark || ''
    searchParams.value.startState = formState.startState
    getList()
  })
}

// 重置当前搜索
const reset = () => {
  spinning.value = true

  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }
  getList()
}

// 查询
import type { SelectProps } from 'ant-design-vue'
const addGroupRef = ref()
const TaskListpRef = ref()
const GoodsListpRef = ref()
const TimerListpRef = ref()

//modal 框方面
const addTask = () => {
  addGroupRef.value.showModal()
}
const handelClickHistory = (item: any) => {
  TaskListpRef.value.showModal(item)
}
const handelClickGoods = (item: any) => {
  GoodsListpRef.value.showModal(item)
}
const handelClickTimer = (item: any) => {
  TimerListpRef.value.showModal(item)
}
</script>

<template>
  <!-- <page-container :title="route.meta.title"> -->
  <a-spin :spinning="spinning">
    <!-- <a-card style="overflow-x: scroll"> -->
    <div class="searchBox">
      <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
        <a-form-item label="备注" name="remark">
          <a-input v-model:value="formState.remark" placeholder="备注" style="width: 200px" />
        </a-form-item>

        <a-form-item label="启动状态" name="startState">
          <a-select
            v-model:value="formState.startState"
            placeholder="请选择"
            style="width: 200px"
            allowClear
          >
            <a-select-option
              v-for="(item, index) in robotStateList"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="search">搜索</a-button>
          <a-button @click="reset">重置</a-button>
          <a-button @click="addTask">添加任务</a-button>
        </a-form-item>
      </a-form>
    </div>

    <div
      class="task-container"
      ref="containerRef"
      style="width: 100%"
      v-if="dataSource.length"
      :style="containerStyle"
    >
      <div v-for="(item, index) in dataSource" class="task-card-item" :key="item.id">
        <a-card hoverable style="width: 300px" title="自动擦亮任务" ref="ItemRef">
          <div class="task-content">
            <div style="color: #000; font-weight: 500" class="marginTOP">
              任务执行日期： {{ timeFormat(item.taskExecuteTime).slice(0, 10) }}
            </div>
            <div style="color: #000; font-weight: 500" class="marginTOP">
              任务执行时间段: {{ item.taskBeginTime }} - {{ item.taskEndTime }}
            </div>
            <div class="marginTOP">
              循环模式:
              <span v-if="item.circulationType == 1">单次循环</span>
              <span v-if="item.circulationType == 2">每日循环</span>
            </div>
            <div class="marginTOP">
              单品间隔:
              <span>
                {{ item.polishIntervalBeginTime }} - {{ item.polishIntervalEndTime }} 分钟
              </span>
            </div>
            <div style="display: flex; align-items: center" class="marginTOP">
              <div>备注：</div>
              <span v-if="!item.isRemarkShow">{{ item.remark }}</span>
              <a-input
                v-else
                v-model:value="item.remark"
                @blur="editRemark(item.id, item.remark)"
                style="width: 160px; border: 0"
              />
              <div>
                <EditOutlined
                  @click="EditRemarkSet(item)"
                  v-if="!item.isRemarkShow"
                  style="margin-left: 10px; color: #1890ff"
                  title="编辑备注"
                />
              </div>
            </div>
            <div class="marginTOP flexS">
              <div>
                宝贝数量:
                <span style="color: red">{{ item.polishProductRelList.length }}</span>
              </div>
              <div>
                <InboxOutlined
                  style="font-size: 18px"
                  @click="handelClickGoods(item)"
                  title="宝贝列表"
                />
              </div>
            </div>
            <div class="marginTOP"><a @click="handelClickTimer(item)">擦亮时间段</a></div>
          </div>
          <template class="ant-card-actions" #actions>
            <div class="left">
              <a-tag color="#87d068" v-if="item.startState">进行中</a-tag>
              <a-tag color="#f50" v-else>已关闭</a-tag>

              <PauseCircleOutlined
                v-if="item.startState"
                style="font-size: 18px"
                @click="updatedStated(item, 0)"
              />
              <PlayCircleOutlined style="font-size: 18px" v-else @click="updatedStated(item, 1)" />
            </div>
            <div>
              <a-progress type="circle" :percent="item.ratio" :size="30" v-if="item.ratio" />
              <a-progress type="circle" :percent="0" :size="30" v-else />
            </div>

            <div>
              <AreaChartOutlined
                style="font-size: 18px"
                @click="handelClickHistory(item)"
                title="任务记录"
              />
              <DeleteOutlined
                style="font-size: 18px; color: red; margin-left: 20px"
                @click="deleteTask(item)"
                title="删除任务"
              />
            </div>
          </template>
        </a-card>
      </div>
    </div>

    <a-empty v-else />

    <div class="task-pagination" v-if="dataSource.length">
      <div></div>
      <a-pagination
        show-size-changer
        v-model:current="currentPage"
        v-model:pageSize="pageSize"
        :total="total"
        @showSizeChange="onShowSizeChange"
        :pageSizeOptions="['14', '28', '42', '56', '70', '84', '98']"
      />
    </div>
    <!-- </a-spin> -->
    <!-- 
      <a-table
        style="overflow-x: scroll"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="changePage"
        rowKey="id"
        :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
      >
        <template #emptyText>
          <a-empty description="暂无数据" />
        </template>

        <template #headerCell="{ column }">
          <template v-if="column.key === 'id'">
            <span>id</span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <div style="width: 150px">{{ record.id }}</div>
          </template>

          <template v-else-if="column.key === 'wechatAccount'">
            <div class="hiddenText">昵称：{{ record.nickName }}</div>
            <div class="hiddenText">微信号：{{ record.wechatAccount }}</div>
            <div class="hiddenText">微信ID：{{ record.wechatId }}</div>
          </template>

          <template v-else-if="column.key === 'avatar'" style="width: 100px">
            <a-popover placement="rightTop">
              <template #content>
                <div class="popoverImg">
                  <img :src="record.avatar" alt="" />
                </div>
              </template>
              <div class="imgBox">
                <img :src="record.avatar" alt="获取失败..." />
              </div>
            </a-popover>
          </template>

          <template v-else-if="column.key === 'createTime'">
            <div v-if="record.createTime.length < 10">-</div>
            <div style="color: #08f72f" v-else>
              {{ timeFormat(record.createTime) }}
            </div>
            <div style="color: red">{{ timeFormat(record.expireTime) }}</div>
            <div>系统编号：{{ record.id }}</div>
          </template>

          <template v-else-if="column.key === 'ip'">
            <div style="width: 180px; text-align: center">{{ record.ip }}</div>
          </template>

          <template v-else-if="column.key === 'rebotState'">
            <a-tag color="blue" v-if="record.robotState == 1">正常</a-tag>
            <a-tag color="red" v-else-if="record.robotState == -1">异常</a-tag>
          </template>

          <template v-else-if="column.key === 'action'">
            <div style="width: 100px; margin: 0; padding: 0">
              <a>充值时长</a>
            </div>
          </template>
        </template>
      </a-table> -->
    <AddGroup ref="addGroupRef" @refresh="getList" :width="1000"></AddGroup>
    <TaskList ref="TaskListpRef" :width="1000"></TaskList>
    <GoodsList ref="GoodsListpRef" :width="600"></GoodsList>
    <TimerList ref="TimerListpRef" :width="600"></TimerList>

    <!-- <h3>正在开发中...</h3> -->
    <!-- </a-card> -->
  </a-spin>
  <!-- </page-container> -->
</template>

<style lang="less" scoped>
.formClass {
  :nth-child(1) {
    // margin-bottom: 2px;
  }
}

.searchBox {
  margin-bottom: 10px;
  display: flex;
  // padding-left: 20px;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}

.task-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
  .task-card-item {
    margin: 10px;
    width: 300px;
    .task-content {
      .marginTOP {
        margin-top: 6px;
      }
      .flexS {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
}
.task-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.ant-card-head-wrapper {
  .ant-card-head-title {
    color: #15181d !important;
    font-weight: 700 !important;
  }
}
.ant-card-head-wrapper .ant-card-actions {
  display: flex;
  align-items: center !important;
}
</style>
